package com.chromatic.competition.service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;

public class SocketClient {
    private final String serverIp;
    private final int serverPort;

    public SocketClient(String serverIp, int serverPort) {
        this.serverIp = serverIp;
        this.serverPort = serverPort;
    }

    public void sendMessage(final String message) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Socket socket = null;
                try {
                    socket = new Socket(serverIp, serverPort);
                    OutputStream out = socket.getOutputStream();
                    out.write(message.getBytes());
                    out.flush();
                    out.close();
                    receiveResponse(socket);
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (socket != null) {
                        try {
                            socket.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }).start();
    }

    private void receiveResponse(Socket socket) throws IOException {
        BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        String responseLine;
        while ((responseLine = input.readLine()) != null) {
            System.out.println("Server: " + responseLine);
            if (responseLine.contains("OK")) {
                break;
            }
        }
        input.close();
    }
}